<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Path Simplifier Example</title>
    <style>
        /* 设置页面高度和宽度 */
        #container, body, html {
            height: 100%;
            width: 100%;
        }

        /* 设置绝对定位 */
        #loadingTip, #panel {
            position: absolute;
            top: 0;
        }

        /* 默认的边距和字体大小 */
        body, html {
            margin: 0;
            font-size: 12px;
        }

        /* 外层容器 */
        #outer-box {
            height: 100%;
            padding-right: 300px;
        }

        /* 面板区域 */
        #panel {
            right: 0;
            width: 300px;
            z-index: 999;
            height: calc(100% - 5px);
            overflow: hidden;
            overflow-y: auto;
        }

        /* 路径容器 */
        #routes-container {
            height: 1200px;
            margin-left: 10px;
        }

        /* 加载提示 */
        #loadingTip {
            z-index: 9999;
            left: 0;
            padding: 3px 10px;
            background: red;
            color: #fff;
            font-size: 13px;
        }

        /* 路径项 */
        .route-item {
            margin-bottom: 10px;
        }

        /* 路径项内部的预格式化文本 */
        .route-item pre {
            margin: 0;
        }

        /* 路径项标题 */
        .route-item h3 {
            margin: 5px 0;
            font-size: 14px;
            cursor: pointer;
        }

        /* 隐藏元素 */
        .hide {
            display: none;
        }

        /* 速度控制器 */
        .speedBox {
            padding: 5px 0;
        }

        /* 速度范围选择器 */
        .speedRange {
            vertical-align: middle;
            margin: 0;
            padding: 0;
            width: 100px;
        }

        /* 标记信息 */
        .markerInfo {
            background: rgba(255, 255, 255, 0.7);
            padding: 2px 5px;
            border: 1px solid #ccc;
            white-space: nowrap;
        }

        #searchPanel {
            position: absolute;
            top: 30px;
            right: 310px;
            z-index: 1000;
            background: #fff;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.3);
            display: flex;
            align-items: center; /* 垂直居中对齐 */
        }

        .search-inputs {
            display: flex;
            flex-direction: column; /* 使子元素垂直排列 */
            margin-right: 10px; /* 在输入框和按钮之间添加一些间距 */
        }

        #searchInput, #searchSelect {
            height: 20px;
            width: 200px;
            margin-bottom: 10px; /* 在输入框和选择框之间添加一些间距 */
        }

        #searchButton {
            height: 40px; /* 调整按钮高度以匹配输入框和选择框的总高度 */
        }
    </style>
</head>
<body>
<div id="outer-box">
    <div id="container"></div>
    <div id="panel">
        <div id="routes-container"></div>
    </div>
    <div id="searchPanel">
        <div class="search-inputs">
            <input type="text" id="searchInput" placeholder="请输入搜索内容">
            <select id="searchSelect">
                <option value="">选择项目部</option>
                @for(item in basicOperatelist!){
                <option value="${item.id}">${item.operateName}</option>
                @}
            </select>
        </div>
        <button id="searchButton" type="button" class="layui-btn layui-bg-purple">搜索</button>
    </div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script type="text/javascript">
    window._AMapSecurityConfig = {
        securityJsCode: "dba528dcd7d571a231a330b532a6cf61",
    };
</script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=4fbb5ae31246fb4337678f7649c87b1b"></script>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<!-- UI组件库 1.0 -->
<script src="https://webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>
<script type="text/javascript">
    // 创建地图
    var map = new AMap.Map('container', {
        zoom: 4
    });

    // 加载 AMap UI 组件
    AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function (PathSimplifier, $) {

        // 检查是否支持 Canvas
        if (!PathSimplifier.supportCanvas) {
            alert('当前环境不支持 Canvas！');
            return;
        }

        // 定义一些颜色 (参数一)
        var colors = [
            "#3366cc", "#dc3912", "#ff9900", "#109618",
            "#990099", "#0099c6", "#dd4477", "#66aa00",
            "#b82e2e", "#316395", "#994499", "#22aa99",
            "#aaaa11", "#6633cc", "#e67300", "#8b0707",
            "#651067", "#329262", "#5574a6", "#3b3eac"
        ];

        // 一、创建 PathSimplifier 实例
        var pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            map: map,
            clickToSelectPath: false,

            // 1.获取路径数据
            getPath: function (pathData, pathIndex) {
                return pathData.path;
            },

            // 2.获取悬停提示
            getHoverTitle: function (pathData, pathIndex, pointIndex) {
                if (pointIndex >= 0) {
                    // 点
                    return pathData.name + '，点:' + pointIndex + '/' + pathData.path.length;
                }
                return pathData.name + '，点数量' + pathData.path.length;
            },

            // 3.渲染选项
            renderOptions: {
                pathLineStyle: {
                    dirArrowStyle: true
                },

                getPathStyle: function (pathItem, zoom) {
                    var color = colors[pathItem.pathIndex],
                        lineWidth = Math.round(4 * Math.pow(1.1, zoom - 3));

                    return {
                        // 隐藏所有路径线
                        // pathLineStyle: {
                        //     lineWidth: 0,
                        //     strokeStyle: 'transparent'
                        // },
                        pathLineStyle: {
                            strokeStyle: color,
                            lineWidth: lineWidth
                        },
                        pathLineSelectedStyle: {
                            lineWidth: lineWidth + 2
                        },
                        pathNavigatorStyle: {
                            fillStyle: color
                        }
                    };
                }
            }
        });

        // 轨迹巡航器数组 (参数二)
        var pathNavigs = [];

        // 二、获取或创建轨迹巡航器
        function getNavg(pathIndex) {
            if (!pathNavigs[pathIndex]) {
                // 创建一个轨迹巡航器
                var navgtr = pathSimplifierIns.createPathNavigator(pathIndex, {
                    loop: true,
                    speed: parseInt($('#speedInp_' + pathIndex).val()),
                    pathNavigatorStyle: {
                        width: 24,
                        height: 48,
                        //使用图片
                        content: PathSimplifier.Render.Canvas.getImageContent("https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png", onload, onerror),
                        strokeStyle: null,
                        fillStyle: null,
                        //经过路径的样式
                        pathLinePassedStyle: {
                            lineWidth: 6,
                            strokeStyle: 'black',
                            dirArrowStyle: {
                                stepSpace: 15,
                                strokeStyle: 'red'
                            }
                        }
                    }
                });

                // 创建标记信息
                var $markerContent = $('<div class="markerInfo"></div>');
                var pathData = pathSimplifierIns.getPathData(pathIndex);
                // $markerContent.html(pathSimplifierIns.getPathData(pathIndex).name);

                console.log("pathData", pathData)

                $markerContent.html(
                    " <strong> 实时位置 </strong> " + '<br/>' +
                    "货运订单号: <span style='color: red;'>HX6-DD-20240904-3903</span>" + '<br/>' +
                    "车牌: <span style='color: red;'>津A 93U32</span>" + '<br/>' +
                    "路线: 北京好想来中心仓 -> 浩海路门店"
                );

                // 创建标记
                navgtr.marker = new AMap.Marker({
                    offset: new AMap.Pixel(12, -10),
                    content: $markerContent.get(0),
                    map: map
                });

                // 获取消息元素
                var $msg = $('#routes-container').find('div.route-item[data-idx="' + pathIndex + '"]').find('.msg');

                // 监听移动事件
                navgtr.on('move', function () {
                    navgtr.marker.setPosition(navgtr.getPosition());
                });

                // 销毁时的回调
                navgtr.onDestroy(function () {
                    pathNavigs[pathIndex] = null;
                    navgtr.marker.setMap(null);
                    $msg.html('');
                });

                // 开始和恢复时记录开始时间和距离
                navgtr.on('start resume', function () {
                    navgtr._startTime = Date.now();
                    navgtr._startDist = this.getMovedDistance();
                });

                // 停止和暂停时更新消息
                navgtr.on('stop pause', function () {
                    navgtr._movedTime = Date.now() - navgtr._startTime;
                    navgtr._movedDist = this.getMovedDistance() - navgtr._startDist;

                    navgtr._realSpeed = (navgtr._movedDist / navgtr._movedTime * 3600);

                    var msgInfo = {
                        '状态': this.getNaviStatus(),
                        '设定速度': this.getSpeed() + ' km/h',
                        '总行进距离': Math.round(this.getMovedDistance() / 1000) + ' km',
                        '本段行进距离': Math.round(navgtr._movedDist / 1000) + ' km',
                        '本段耗时': (navgtr._movedTime / 1000) + ' s',
                        '本段实际速度': Math.round(navgtr._realSpeed) + ' km/h'
                    };

                    $msg.html('<pre>' + JSON.stringify(msgInfo, null, 2) + '</pre>');

                    refreshNavgButtons();
                });

                // 移动时更新消息
                navgtr.on('move', function () {
                    var msgInfo = {
                        '状态': this.getNaviStatus(),
                        '设定速度': this.getSpeed() + ' km/h',
                        '总行进距离': Math.round(this.getMovedDistance() / 1000) + ' km'
                    };

                    $msg.html('<pre>' + JSON.stringify(msgInfo, null, 2) + '</pre>');
                });

                pathNavigs[pathIndex] = navgtr;
            }

            return pathNavigs[pathIndex];
        }

        // 轨迹巡航按钮配置
        var navigBtnsConf = [{
            name: '开始巡航',
            action: 'start',
            enableExp: 'navgStatus === "stop" || navgStatus === "pause"'
        }, {
            name: '暂停',
            action: 'pause',
            enableExp: 'navgStatus === "moving"'
        }, {
            name: '恢复',
            action: 'resume',
            enableExp: 'navgStatus === "pause"'
        }, {
            name: '停止',
            action: 'stop',
            enableExp: 'navgStatus === "moving"'
        }, {
            name: '销毁',
            action: 'destroy',
            enableExp: 'navgExists'
        }];

        // 刷新轨迹巡航按钮状态
        function refreshNavgButtons() {
            $('#routes-container').find('div.route-item').each(function () {
                var pathIndex = parseInt($(this).attr('data-idx'), 0); // 获取路径索引
                if (pathIndex < 0) {
                    return; // 如果路径索引无效，则跳过
                }
                var navgStatus = 'stop', // 默认状态为停止
                    navgExists = !!pathNavigs[pathIndex]; // 检查是否存在该路径的巡航实例
                if (navgExists) {
                    navgStatus = pathNavigs[pathIndex].getNaviStatus(); // 获取当前的巡航状态
                }
                $(this).find('.navigBtn').each(function () {
                    var btnIdx = parseInt($(this).attr('data-btnIdx'));
                    $(this).prop('disabled', !eval(navigBtnsConf[btnIdx].enableExp)); // 根据配置启用或禁用按钮
                });
            });
        }

        // 初始化单个路径项
        function initRouteItem(pathData, idx) {
            var $routeItem = $('<div class="route-item"></div>');
            $routeItem.attr('data-idx', idx);
            $('<h3/>')
                .css({
                    color: colors[idx]
                })
                .html(pathData.name + '(点数： ' + pathData.path.length + ')')
                .appendTo($routeItem)
                .on('click', function () {
                    pathSimplifierIns.setSelectedPathIndex(idx);
                });

            for (var i = 0, len = navigBtnsConf.length; i < len; i++) {
                $('<button class="navigBtn" data-btnIdx="' + i + '" data-act="' + navigBtnsConf[i].action + '"></button>')
                    .html(navigBtnsConf[i].name)
                    .appendTo($routeItem);
            }

            var $speedBox = $('<div class="speedBox"></div>').appendTo($routeItem);
            var speedTxt = $('<span></span>').appendTo($speedBox);
            var speedRangeInput = $('<input id="speedInp_' + idx + '" class="speedRange" type="range" min="10" max="1000" step="10" value="100" />').appendTo($speedBox);

            function updateSpeedTxt() {
                var speed = parseInt(speedRangeInput.val(), 10);
                speedTxt.html('时速：' + speed + ' km/h');
                if (pathNavigs[idx]) {
                    pathNavigs[idx].setSpeed(speed);
                }
            }

            speedRangeInput.on('change', updateSpeedTxt);
            updateSpeedTxt();

            $('<div class="msg"></div>').appendTo($routeItem);
            $routeItem.appendTo('#routes-container');
        }

        // 初始化路径容器
        function initRoutesContainer(data) {
            $('#routes-container').on('click', '.navigBtn', function () {
                var pathIndex = parseInt($(this).closest('.route-item').attr('data-idx'), 0);
                var navg = getNavg(pathIndex);
                navg[$(this).attr('data-act')]();
                refreshNavgButtons();
            });
            for (var i = 0, len = data.length; i < len; i++) {
                initRouteItem(data[i], i);
            }
            refreshNavgButtons();
        }

        // 全局变量
        window.pathSimplifierIns = pathSimplifierIns;

        // 显示加载提示
        $('<div id="loadingTip">加载数据，请稍候...</div>').appendTo(document.body);

        // 获取路径数据
        $.getJSON('https://a.amap.com/amap-ui/static/data/big-routes.json', function (d) {

            var dd = [{"path":[["117.229083","36.646043"],["117.231974","36.646628"],["117.235058","36.646905"],["117.238291","36.646669"],["117.238419","36.646664"],["117.238533","36.646664"],["117.238541","36.646664"],["117.239075","36.646637"],["117.239082","36.646637"],["117.240665","36.64656"],["117.241356","36.646511"],["117.242146","36.646314"],["117.24258","36.646153"],["117.24324","36.645809"],["117.243594","36.645557"],["117.243916","36.645278"],["117.244109","36.64508"],["117.244361","36.644758"],["117.244576","36.644415"],["117.245252","36.643122"]],"name":"鲁D66661-CS5-DD-20240909-3906"}]

            // 移除加载提示元素
            $('#loadingTip').remove();


            // 使用处理后的数据初始化路径简化器实例
            pathSimplifierIns.setData(dd);
            console.log("查询高德信息:",pathSimplifierIns);

            // 初始化界面上的路线容器
            initRoutesContainer(dd);
        });
    });
</script>
</body>
</html>